﻿#include "SendSocketMsg.h"
#include "protocolstream.h"
#include "Msg.h"

#include <QString>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
SendSocketMsg::SendSocketMsg(QTcpSocket *socket, QObject *parent)
    : QObject(parent),
      m_pTcpSocket(socket)
{

}

void SendSocketMsg::SltSendMsg(int32_t cmd, const QJsonDocument& data)
{
    qDebug() << "SltSendMsg() thread" << QThread::currentThreadId();
    QByteArray msgData = data.toJson();
    qDebug() << "json data: " << msgData;
    std::string outbuf;
    yt::BinaryWriteStream3 writeStream(&outbuf);
    writeStream.Write(cmd);
    writeStream.Write(m_seq);
    writeStream.Write(msgData.constData(), msgData.size());
    writeStream.Flush();

    SendPackage(outbuf.c_str(), outbuf.length());
    m_seq++;
}

void SendSocketMsg::SendPackage(const char* str, int32_t length)
{
    QByteArray sendData;
    msg header = { (int32_t)length };
    qDebug() << "Send data, header length:" << sizeof(header) << ", body length:" << length;
    sendData.append((const char*)&header, sizeof(header));
    sendData.append(str, length);
    m_pTcpSocket->write(sendData);
}
